from lib import itchat
import requests, time
import io

# 根据行为列表操作机器人行为，行为监听后续补充
def handler_actions(action_list):
    '''
    :param action_list: 行为列表，暂定行为枚举如下
        发送文本消息
        {
            "name": "send_text",
            "content": "测试文本",
            "toUserName": "@27e2cb58830b3f219b674b37a709906d043af73eb8abbd9acb4b6edee38be521",
        }
        发送图片(本地图片)消息
        {
            "name": "send_local_image",
            "content": "/Users/jiayifei/codes/github/mjrobot/static/images/img.png",
            "toUserName": "@27e2cb58830b3f219b674b37a709906d043af73eb8abbd9acb4b6edee38be521",

        }
        发送图片(网络图片)消息
        {
            "name": "send_remote_image",
            "content": "https://inews.gtimg.com/newsapp_bt/0/14210535246/1000",
            "proxies": {"http": "http://127.0.0.1:7890", "https": "http://127.0.0.1:7890"},
            "toUserName": "@27e2cb58830b3f219b674b37a709906d043af73eb8abbd9acb4b6edee38be521",
        }
    :return:
    '''
    if len(action_list) == 0:
        return None
    else:
        for action in action_list:
            # todo 字段完整性判断
            if action["name"] == "send_text":
                # 如果是发文本消息，则必须包含
                itchat.send(action["content"], toUserName=action["toUserName"])
            elif action["name"] == "send_local_image":
                image_path = action["content"]
                image_storage = io.BytesIO()
                with open(image_path, mode="rb") as image_file:
                    image_storage.write(image_file.read(1024))
                    for block in image_file.read(1024):
                        image_storage.write(block)

                image_storage.seek(0)
                itchat.send_image(image_storage, toUserName=action["toUserName"])
            elif action["name"] == "send_remote_image":
                img_url = action["content"]
                pic_res = requests.get(
                    url = img_url,
                    proxies = action["proxies"],
                    stream = True
                )
                image_storage = io.BytesIO()
                for block in pic_res.iter_content(1024):
                    image_storage.write(block)
                image_storage.seek(0)
                itchat.send_image(image_storage, toUserName=action["toUserName"])
            else:
                pass
            pass
        return None

